package com.jltx.xq.coroutinesapp

import kotlinx.coroutines.suspendCancellableCoroutine
import retrofit2.Call
import retrofit2.Callback
import retrofit2.HttpException
import retrofit2.Response
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException

/**
 * @author aidenquan
 *         Created by junlintianxia on 2021/07/09.
 */
suspend fun <T> Call<T>.awaitKt(): T = suspendCancellableCoroutine { continuation ->
    continuation.invokeOnCancellation {
        cancel()
    }
    enqueue(object : Callback<T> {
        override fun onFailure(call: Call<T>, t: Throwable) {
            if (continuation.isCancelled) return
            continuation.resumeWithException(t)
        }

        override fun onResponse(call: Call<T>, response: Response<T>) {
            response.takeIf { it.isSuccessful }?.body()?.also {
                continuation.resume(it)
            } ?: continuation.resumeWithException(HttpException(response))
        }

    })
}